﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Data.SqlClient;

namespace TSQL_Express
{
    public partial class CoreExpress : Form
    {
        //sql 连接语句
        public string GetSqlSource = "";
        public CoreExpress()
        {
            InitializeComponent();

            #region 身份验证
            //身份验证
            comLoad.SelectedIndex = 0;
            txtid.Enabled = false;
            txtpas.Enabled = false;
            comLoad.SelectedIndexChanged += (s, e) =>
            {
                if (comLoad.SelectedIndex == 0)
                {
                    txtid.Enabled = false;
                    txtpas.Enabled = false;
                    return;
                }
                txtid.Enabled = true;
                txtpas.Enabled = true;
            };
            #endregion

            #region sql登录

            //sql登录
            btnOpen.Click += (s, e) =>
            {
                var gex = txtid.Text == "" ? "用户名不能为空" : txtpas.Text == "" ? "密码不能为空" : (object)true;
                if (txtfw.Text == "")
                {
                    MessageBox.Show("服务器名称不能为空！");
                    return;
                }
                if (comLoad.SelectedIndex == 0)
                {
                    GetSqlSource = string.Format("Data Source={0};Initial Catalog=master;Integrated Security=True",txtfw.Text);
                    GetDataShow();
                    return;
                }
                if (gex.GetType() == typeof(string))
                {
                    MessageBox.Show(gex.ToString());
                    return;
                }
                GetSqlSource = string.Format("Data Source={0};Initial Catalog=master;User ID={1};Password={2}", txtfw.Text, txtid.Text, txtpas.Text);
                GetDataShow();
            };

            #endregion

            #region 获取目录信息

            btnDir.Click += (s, e) =>
            {
                FolderBrowserDialog fb = new FolderBrowserDialog();
                if (fb.ShowDialog() == DialogResult.OK)
                {
                    txtPath.Text = string.Empty;
                    txtPath.Text = fb.SelectedPath;
                    LoadSql(txtPath.Text);
                }
            };

            #endregion

            #region 获取文件信息

            btnFile.Click += (s, e) =>
            {
                OpenFileDialog fg = new OpenFileDialog();
                fg.Filter = "sql文件(*.sql)";
                if (fg.ShowDialog() == DialogResult.OK)
                {
                    txtPath.Text = string.Empty;
                    txtPath.Text = fg.FileName;
                    LoadSql(txtPath.Text);
                }
            };

            #endregion

            #region 执行操作

            //异常报告
            List<object> trymsg = new List<object>();

            //执行操作
            btnLoad.Click += (s, e) =>
            {
                trymsg.Clear();
                TryView.Items.Clear();
                if (raddos.Checked)
                {
                    //dos
                    for (int i = 0; i < SqlViewShow.Items.Count; i++)
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        string dos = DOSLoad(comLoad.SelectedIndex == 0 ? false : true) + SqlViewShow.Items[i].SubItems[1].Tag.ToString();
                        string loadmxg = SqlExpress.Execute(dos, Convert.ToInt32(DosHm.Value));
                        sw.Stop();
                        TimeSpan ts = sw.Elapsed;
                        string tm = ts.Seconds == 0 ? "1秒" : ts.Seconds.ToString() + "秒";
                        ListViewItem lv = new ListViewItem(i.ToString());
                        lv.UseItemStyleForSubItems = false;
                        lv.SubItems.Add(SqlViewShow.Items[i].SubItems[1].Text);
                        string contry = loadmxg.Contains("行受影响") ? "执行成功" : "执行失败(双击查看)";
                        bool Istry = loadmxg.Contains("行受影响") ? true : false;
                        lv.SubItems.Add(contry).ForeColor = Istry ? Color.Green : Color.Red;
                        lv.SubItems.Add(tm);
                        TryView.Items.Add(lv);
                        //赋值
                        if (!Istry)
                        {
                            trymsg.Add(new string[] { SqlViewShow.Items[i].SubItems[1].Text, loadmxg });
                        }
                    }
                }
            };

            TryView.DoubleClick += (s, e) =>
            {
                CoreTryShow cs = new CoreTryShow();
                string mxg = "";
                for (int i = 0; i < trymsg.Count; i++)
                {
                    if (((string[])trymsg[i])[0].ToString() == TryView.FocusedItem.SubItems[1].Text)
                    {
                        //取值
                        mxg = ((string[])trymsg[i])[1].ToString();
                    }
                }
                cs.txtbm.Text = TryView.FocusedItem.SubItems[1].Text;
                cs.textBox1.Text = mxg;
                cs.ShowDialog();
            };
            #endregion


        }

        #region 导入sql文件

        //导入sql文件
        public void LoadSql(string path)
        {
            SqlViewShow.Items.Clear();
            if (Directory.Exists(path))
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                FileInfo[] file = dir.GetFiles();
                int xa = 0;

                foreach (FileInfo info in file)
                {
                    xa = xa + 1;
                    if (Path.GetExtension(info.FullName) == ".sql")
                    {
                        ListViewItem lv = new ListViewItem(xa.ToString());
                        lv.SubItems.Add(Path.GetFileName(info.FullName)).Tag = info.FullName;
                        lv.SubItems.Add(GetSize(info.FullName));
                        SqlViewShow.Items.Add(lv);
                    }
                }
                return;
            }
            ListViewItem ts = new ListViewItem("0");
            ts.SubItems.Add(Path.GetFileName(path)).Tag = path;
            ts.SubItems.Add(GetSize(path));
            SqlViewShow.Items.Add(ts);
        }

        #endregion

        #region 获取数据库列表

        public void GetDataShow()
        {
            DataShow.Items.Clear();
            if (SqlExpress.CoreDBList(GetSqlSource) != null)
            {
                for (int i = 0; i < SqlExpress.CoreDBList(GetSqlSource).Count; i++)
                {
                    ListViewItem lv = new ListViewItem("# - " + i.ToString());
                    lv.SubItems.Add(SqlExpress.CoreDBList(GetSqlSource)[i]);
                    DataShow.Items.Add(lv);
                }
                tsLoad.Text = txtfw.Text + " 连接成功...";
                return;
            }
            MessageBox.Show("数据库连接失败,请检查后重试！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            tsLoad.Text = "连接失败...";
            
        }

        #endregion

        #region 生成DOS命令

        //生成DOS命令
        public string DOSLoad(bool login)
        {
            string sql = "";
            if (login)
            {
                sql = string.Format("osql -S {0} -U {1} -P {2} -i ", txtfw.Text, txtid.Text, txtpas.Text);
            }
            else
            {
                sql = string.Format("osql -S {0} -E -i ", txtfw.Text);
            }
            return sql;
        }

        #endregion

        #region 计算指定文件大小

        public string GetSize(String path)
        {
            return CountSize(GetFilesSize(path));
        }

        //计算指定文件大小
        public long GetFilesSize(String path)
        {
            long length = 0;
            FileInfo file = new FileInfo(path);
            length = file.Length;
            return length;
        }

        #endregion

        #region 转换文件大小函数

        /// <summary>  
        /// 计算文件大小函数(保留两位小数),Size为字节大小  
        /// </summary>  
        /// <param name="Size">初始文件大小</param>  
        /// <returns></returns>  
        public string CountSize(long Size)
        {
            string m_strSize = "";
            long FactSize = 0;
            FactSize = Size;
            if (FactSize < 1024.00)
                m_strSize = FactSize.ToString("F2") + " Byte";
            else if (FactSize >= 1024.00 && FactSize < 1048576)
                m_strSize = (FactSize / 1024.00).ToString("F2") + " Kb";
            else if (FactSize >= 1048576 && FactSize < 1073741824)
                m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " Mb";
            else if (FactSize >= 1073741824)
                m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " Gb";
            return m_strSize;
        }

        #endregion
    }
}
